#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>

#include "sound.h"

#define PACKAGE_COUNT 0x1000  //数据包个数

unsigned char buff[BUFFER_SIZE * PACKAGE_COUNT]; //大缓冲区

struct sockaddr_in toaddr;
struct sockaddr_in localaddr;

int socketfd;

/* 话筒端软件除了主动发送之外，还需要作为服务端被取数据
*/
pthread_t pthread_t_timer0;
pthread_t pthread_t_server;

/*这是一个定时轮寻线程, 寻找没有找到的数据包,并发送重新获取音频数据包指令给话筒端
 */
void* timer0_thread_function(void* p)
{
    unsigned char recvbuff[2048];
    
    struct sockaddr_in *src_addr;
    socklen_t addrlen;
    
    printf("timer0_thread_function\n");
    
    while(1)
    {
	    int recvlen = recvfrom(socketfd, recvbuff, sizeof(recvbuff), 0, (struct sockaddr*)src_addr, &addrlen);
	    if (recvlen == -1)
	    {
	        perror("recvfrom");
	    }
	    else if(recvlen > 0)
	    {
	        printf("收到再次请求数据\n");
	    }
	    //usleep(1*1000);
    }
}

/*音频数据包主动发送线程*/
void* server_thread_function(void* p)
{
    printf("server_thread_function \n");
    
    int i = 0;

    while(i < PACKAGE_COUNT)
    {
	  printf("%d\n", i);
	  //size_t len;
	  
	  talkdata_t talkdata;
	  
	  talkdata.header.Frameno  = i++; //帧序号
	  talkdata.header.Framesize = BUFFER_SIZE;//帧长
	  talkdata.header.to_addr = toaddr.sin_addr;
	  
	  memcpy(talkdata.buffer, &buff[i*BUFFER_SIZE], BUFFER_SIZE);
		  
	    sendto(socketfd, &talkdata, sizeof(talkdata), 0, (struct sockaddr*)&toaddr, sizeof(struct sockaddr));
			    
	    usleep(19*1000);//20ms一个音频数据包
    }
}

/*初始化数据*/
int init()
{
    int i;
    for (i=0;i<sizeof(buff);i++)
    {
        buff[i] = i;
    }
    
    socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    
    if(socketfd == -1)
    {
        perror("create udp socket");
        return;
    }
    
    toaddr.sin_family = AF_INET;
    toaddr.sin_port = htons(20000);
    toaddr.sin_addr.s_addr = inet_addr("192.168.68.233");     
    
    
    localaddr.sin_family = AF_INET;
    localaddr.sin_port = htons(20000);
    localaddr.sin_addr.s_addr = INADDR_ANY;
    if(bind(socketfd, (struct sockaddr*)&localaddr, sizeof(localaddr)) == -1)
    {
      perror("bind");
      return;
    }
}

int main(void)
{
	printf("udp server program\n");

	init();
	
	pthread_create(&pthread_t_timer0, NULL, timer0_thread_function, NULL);	
	pthread_create(&pthread_t_server, NULL, server_thread_function, NULL);
	
	pthread_join(pthread_t_timer0, NULL);
	usleep(1000);	
	pthread_join(pthread_t_server, NULL);	
	usleep(1000);
	
	return 0;
}


